
import axios from 'axios'
import Utils from '@/utils/common'
import Cookies from 'js-cookie'
import Msg from '@/utils/msg'
import Auth from '@/auth'
import Store from '@/store'

console.log("### axios 拦截设置....")

axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'



// 拦截request,设置全局请求为ajax请求
axios.interceptors.request.use((config) => {
    // console.log("config:",config)
    let data = config.data
    // console.log('showLoading:',data.showLoading)
    if(data.showLoading){
        Msg.showLoading()
    }
    let form = new FormData() // 创建form对象
    form.append('token',Store.getters.token)
    for (var key in data) {
        if(key!='showLoading'){
            form.append(key, data[key])
        }
    }
    config.data = form

    return config
})

// 拦截响应response，并做一些错误处理
axios.interceptors.response.use((response) => {
    Msg.hideLoading()
    const json = response.data
    if(json.code==-1){ //登录身份已过期
      Cookies.set('auth_token', null)
      // var arr = location.href.split("#");
      // if(arr.length>1){
      //   Cookies.set('next', arr[1])
      // }
      location.reload();
    }else{
      return json;
    }

    // 若不是正确的返回code，且已经登录，就抛出错误
    // const err = new Error(data.description)
    // err.data = data
    // err.response = response
    // throw err

}, (err) => { // 这里是返回状态码不为200时候的错误处理
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.message = '请求错误'
                break

            case 401:
                err.message = '未授权，请登录'
                break

            case 403:
                err.message = '拒绝访问'
                break

            case 404:
                err.message = `请求地址出错: ${err.response.config.url}`
                break

            case 408:
                err.message = '请求超时'
                break

            case 500:
                err.message = '服务器内部错误'
                break

            case 501:
                err.message = '服务未实现'
                break

            case 502:
                err.message = '网关错误'
                break

            case 503:
                err.message = '服务不可用'
                break

            case 504:
                err.message = '网关超时'
                break

            case 505:
                err.message = 'HTTP版本不受支持'
                break

            default:
        }
    }

    return Promise.reject(err)
})
